package cn.com.taiji.oospub.wechat.common.wxpay.pay;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class MainServlet extends HttpServlet {

	@Override
	public void init() throws ServletException {
		System.out.println("============");
		super.init();
	}
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	//网页授权获取用户信息
	@Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		HashMap<String,Object> map = new HashMap<String,Object>(); 
//		map.put("appId", "wx2faec6d97bb8d50a");
//		map.put("mch_id", "1316199301");
//		map.put("nonceStr", TenpayUtil.buildRandom(32));
//		String sign = MD5.sign("123", "sdekdib83jd84jd3mf92orid8bkd90zx", "UTF-8");
//		System.out.println(sign);
//		map.put("sign", sign);
//		map.put("body", "测试商品");
//		map.put("out_trade_no", 1234567);
//		map.put("total_fee", 0.01);
//		String ip =  CommonTools.getIp(request);
//		System.out.println(ip);
//		map.put("spbill_create_ip", ip);
//		String notify_url="https://api.mch.weixin.qq.com/pay/unifiedorder";
//		map.put("notify_url", notify_url);
//		map.put("trade_type", "NATIVE");
//		byte[] xml = MainServlet.callMapToXML(map);
//		String url ="https://api.mch.weixin.qq.com/pay/unifiedorder?"+xml;
//		response.sendRedirect(url);
		
//		response.setHeader("content-type","text/html;charset=UTF-8");
//		response.getWriter().println(xml);
		
		
		
//		HashMap<String, String> paramMap = new HashMap<>();
//		String notify_url="https://education.aramark.cn/pos_pay/create_direct_pay_by_user-JAVA-UTF-8/notify_url.jsp";
//		
//	    paramMap.put("appid", "wx534942d99e0e366a"); //appid：每个公众号都有一个appid
//	    paramMap.put("mch_id", "11111111111"); //商户号：开通微信支付后分配
//	    //随机数
//	    paramMap.put("nonce_str", getRandomStringByLength(32));  
//	    paramMap.put("body", "香辣烤翅"); //商品描述
//	    //商户订单号：用户id + “|” + 随机16位字符
//	    paramMap.put("out_trade_no", "fan" + "|" + getRandomStringByLength(16)); 
//	    paramMap.put("total_fee", "0.01"); //金额必须为整数  单位为分
//	    paramMap.put("spbill_create_ip", CommonTools.getIp(request)); //本机的Ip
//	    paramMap.put("notify_url", notify_url); //支付成功后，回调地址
//	    paramMap.put("trade_type", "NATIVE"); //交易类型
//	    paramMap.put("product_id", "100001"); // 商户根据自己业务传递的参数 当trade_type=NATIVE时必填
//	    //根据微信签名规则，生成签名。随机参数可以在商户后台管理系统中进行设置。
//	    paramMap.put("sign", PaymentUtil.getSignature(paramMap, "beGPax3F1EtxxxxxxofcerMRqNvt9XJ2"));
//
//	    String xmlData = PaymentUtil.mapToXml(paramMap);//把参数转换成XML数据格式
//
//	    String codeUrl = getCodeUrl(xmlData);   //获取二维码链接
//	    String ip =  CommonTools.getIp(request);
//	    System.out.println(ip+"========");
//	    return PaymentUtil.encodeQrcode(codeUrl);   //将二维码链接信息编码成二维码图片，用BufferedImage对象表示
		
	}
	public static byte[] callMapToXML(Map map) {  
//        logger.info("将Map转成Xml, Map：" + map.toString());  
        StringBuffer sb = new StringBuffer();  
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><bizdata>");  
        mapToXMLTest2(map, sb);  
        sb.append("</bizdata>");  
//        logger.info("将Map转成Xml, Xml：" + sb.toString());  
        try {  
            return sb.toString().getBytes("UTF-8");  
        } catch (Exception e) {  
//            logger.error(e);  
        }  
        return null;  
    }  
  
	public static void mapToXMLTest2(Map map, StringBuffer sb) {  
        Set set = map.keySet();  
        for (Iterator it = set.iterator(); it.hasNext();) {  
            String key = (String) it.next();  
            Object value = map.get(key);  
            if (null == value) {
                value = "";
            }
            if ("java.util.ArrayList".equals(value.getClass().getName())) {
                ArrayList list = (ArrayList) map.get(key);  
                sb.append("<" + key + ">");  
                for (int i = 0; i < list.size(); i++) {  
                    HashMap hm = (HashMap) list.get(i);  
                    mapToXMLTest2(hm, sb);  
                }  
                sb.append("</" + key + ">");  
  
            } else {  
                if (value instanceof HashMap) {  
                    sb.append("<" + key + ">");  
                    mapToXMLTest2((HashMap) value, sb);  
                    sb.append("</" + key + ">");  
                } else {  
                    sb.append("<" + key + ">" + value + "</" + key + ">");  
                }  
  
            }  
  
        }  
    } 
	/**
     * 获取一定长度的随机字符串
     * @param length 指定字符串长度
     * @return 一定长度的字符串
     */
    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

	/**
	 * 获取二维码链接
	 * @param xmlData
	 * @return
	 */
//	private String getCodeUrl(String xmlData) {
//	    String resXml = HttpUtil.postData(WX_PAYMENT_API_URL, xmlData);
//	    String code_url = "";
//	    Map<String, Object> map;
//	    try {
//	        map = PaymentUtil.getMapFromXML(resXml);
//	        Object returnCode = map.get("return_code");
//	        if(PaymentUtil.SUCCESS.equals(returnCode)) {
//	            Object resultCode = map.get("result_code");
//	            if(PaymentUtil.SUCCESS.equals(resultCode)) {
//	                code_url = map.get("code_url").toString();
//	            }
//	        }
//	    } catch (Exception e) {
//	        return "";
//	    }
//
//	    return code_url;
//	}
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	@Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
